package servlet;

import com.alibaba.fastjson.JSON;
import entity.Memo;
import service.MemoService;
import service.impl.MemoServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/MemoServlet")
public class MemoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");

        PrintWriter out = resp.getWriter();
        MemoService service = new MemoServiceImpl();

        String opr = req.getParameter("opr");
        if (opr.equals("count")){
            int uid = Integer.parseInt(req.getParameter("uid"));
            int r = service.selectMemoCount(uid);
            out.print(r);
        }else if (opr.equals("list")){
            int mtid = Integer.parseInt(req.getParameter("mtid"));
            List<Memo> list = service.selectMemos(mtid);
            String listJSON = JSON.toJSONString(list);
            out.print(listJSON);
        }else if (opr.equals("one")){
            int mid = Integer.parseInt(req.getParameter("mid"));
            Memo memo = service.selectMemo(mid);
            String strJSON = JSON.toJSONString(memo);
            out.print(strJSON);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
